package com.uzai.console.utils;

import com.uzai.console.annotation.DataPanel;
import com.uzai.console.enums.ReportPanelTypeEnum;
import com.uzai.console.service.reportpanel.BaseDataPanelService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author mingyang.chen create in 2023/4/3 16:29
 */
@Component
public class DataPanelHolder implements ApplicationContextAware {

    private final Map<Integer, BaseDataPanelService> dataPanelServiceCache = new HashMap<>(8);

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取到所有的数据面板业务方法
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(DataPanel.class);
        for (Object value : beansWithAnnotation.values()) {
            if (value instanceof BaseDataPanelService) {
                BaseDataPanelService dataPanelService = (BaseDataPanelService) value;
                ReportPanelTypeEnum dataPanelType = dataPanelService.getDataPanelType();
                dataPanelServiceCache.put(dataPanelType.getId(), dataPanelService);
                continue;
            }
            throw new IllegalStateException("DataPanel注解所处类非BaseDataPanelService子类");
        }
    }

    public BaseDataPanelService matchDataPanel(Integer type) {
        return dataPanelServiceCache.get(type);
    }
}
